package com.idnx.mynewsdemo.view;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;


import com.idnx.mynewsdemo.R;
import com.idnx.mynewsdemo.database.DBHelper;
import com.idnx.mynewsdemo.http.VideoPlayerView;
import com.idnx.mynewsdemo.presenter.FileOperations;
import com.idnx.mynewsdemo.presenter.VideoPlayerPresenter;

import java.util.List;

public class VideoPlayerActivity extends AppCompatActivity implements VideoPlayerView {
    private VideoPlayerPresenter presenter;
    private SeekBar seekBar;
    private ImageButton btnTouxiang;
    private TextView descriptionView;
    private TextView tagsView;
    private VideoView videoView; // VideoView实例
    private boolean isPlaying = true; // 初始状态为播放状态
    private DBHelper dbHelper; // 数据库帮助类实例
    private FileOperations fileOperations; // FileOperations实例

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);

        seekBar = findViewById(R.id.time);
        videoView = findViewById(R.id.MyVideo); // 获取VideoView
        fileOperations = new FileOperations(this); // 初始化FileOperations实例
        fileOperations.copyFilesToAppDirectory(); // 复制文件到应用目录
        fileOperations.scanAndUploadFilesToDatabase(); // 扫描目录并将文件信息上传到数据库
        SeekBar seekBar = findViewById(R.id.time);
        TextView times = findViewById(R.id.times);

        dbHelper = new DBHelper(this); // 创建DBHelper实例
        List<String> videoPaths = dbHelper.getVideoPaths(); // 从数据库获取视频路径列表
        presenter = new VideoPlayerPresenter(this, videoPaths); // 将视频路径列表传递给Presenter


        videoView.setOnTouchListener(new View.OnTouchListener() {
            private static final int TAP_THRESHOLD_DP = 5;
            private static final int TAP_THRESHOLD_MS = 200;
            private float xDown, yDown;
            private long downTime;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 记录按下时的X和Y坐标以及时间
                        xDown = event.getX();
                        yDown = event.getY();
                        downTime = System.currentTimeMillis();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        // 如果移动的距离超过了阈值，则不认为是点击
                        if (Math.abs(event.getX() - xDown) > TAP_THRESHOLD_DP * v.getContext().getResources().getDisplayMetrics().density
                                || Math.abs(event.getY() - yDown) > TAP_THRESHOLD_DP * v.getContext().getResources().getDisplayMetrics().density) {
                            return true;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        // 检查是否是快速点击（用于播放/暂停）
                        if (System.currentTimeMillis() - downTime <= TAP_THRESHOLD_MS) {
                            // 检查点击位置是否在VideoView内部，以及是否是点击而不是滑动
                            if (event.getX() >= xDown - TAP_THRESHOLD_DP * v.getContext().getResources().getDisplayMetrics().density
                                    && event.getX() <= xDown + TAP_THRESHOLD_DP * v.getContext().getResources().getDisplayMetrics().density
                                    && event.getY() >= yDown - TAP_THRESHOLD_DP * v.getContext().getResources().getDisplayMetrics().density
                                    && event.getY() <= yDown + TAP_THRESHOLD_DP * v.getContext().getResources().getDisplayMetrics().density) {
                                // 执行播放/暂停操作
                                if (isPlaying) {
                                    videoView.pause();
                                    isPlaying = false;
                                } else {
                                    videoView.start();
                                    isPlaying = true;
                                }
                            }
                        }
                        // 检查是否是滑动操作（用于上一个/下一个视频）
                        float upY = event.getY();
                        if (upY > yDown) {
                            // 下滑，下一个视频
                            presenter.nextVideo();
                        } else if (upY < yDown) {
                            // 上滑，上一个视频
                            presenter.previousVideo();
                        }
                        return true;
                    default:
                        return false;
                }
                return false;
            }
        });



        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    videoView.seekTo(progress); // 调整视频进度
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                videoView.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                videoView.start();
            }
        });

        // 设置视频路径并播放第一个视频
        if (!videoPaths.isEmpty()) {
            String firstVideoPath = videoPaths.get(0);
            Uri videoUri = Uri.parse(firstVideoPath);
            videoView.setVideoURI(videoUri);

            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    videoView.start(); // 开始播放视频
                }
            });

            videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.e("VideoView", "Error: " + what + ", Extra: " + extra);
                    videoView.stopPlayback(); // 停止播放并释放资源
                    return true;
                }
            });

            Log.d("VideoView", "Playing video: " + firstVideoPath);
        }


        // 从数据库获取视频路径列表
        if (!videoPaths.isEmpty()) {
            String firstVideoPath = videoPaths.get(0); // 获取第一个视频路径
            videoView.setVideoURI(Uri.parse(firstVideoPath)); // 设置视频路径到 VideoView


//        // 获取第一个视频的信息
//            Cursor cursor = dbHelper.getAllVideoPaths();
//            if (cursor.moveToFirst()) {
//                String firstVideoPath = cursor.getString(cursor.getColumnIndex(DBHelper.getVideoPathColumn()));
//                String firstVideoId = cursor.getString(cursor.getColumnIndex(DBHelper.getIdColumn()));
//                setVideoInfo(firstVideoId, firstVideoPath);
//            }
//            cursor.close();
//
//
//        private void setVideoInfo(String videoId, String videoPath) {
//            // 设置用户头像
//            String userId = "1"; // 假设第一个视频的用户ID为1
//            String avatarPath = dbHelper.getAvatarPathByUserId(userId);
//            Glide.with(this).load(avatarPath).into(btnTouxiang); // 使用 Glide 加载图片
//
//            // 设置视频描述
//            String description = dbHelper.getDescriptionByVideoId(videoId);
//            descriptionView.setText(description);
//
//            // 设置视频标签
//            List<String> tags = dbHelper.getTagsByVideoId(videoId);
//            StringBuilder tagsText = new StringBuilder();
//            for (String tag : tags) {
//                tagsText.append(tag).append(" ");
//            }
//            tagsView.setText(tagsText.toString().trim());
//        }
//
//





            videoView.setOnPreparedListener(mp -> {
                int duration = videoView.getDuration();
                seekBar.setMax(duration);  // 设置进度条的最大值
            });

            videoView.setOnInfoListener((mp, what, extra) -> {
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    // 视频开始渲染时，更新进度
                    int progress = videoView.getCurrentPosition();
                    seekBar.setProgress(progress);
                }
                return true;
            });

            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        videoView.seekTo(progress);  // 用户拖动进度条时，更新视频播放位置
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    videoView.pause();  // 用户开始拖动进度条时暂停视频
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    videoView.start();  // 用户停止拖动进度条时继续播放视频
                }
            });

            // 更新 TextView 显示的时间
            videoView.start();
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    int current = videoView.getCurrentPosition();
                    int total = videoView.getDuration();
                    int minutes = (int) (current / (60 * 1000));
                    int seconds = (int) ((current % (60 * 1000)) / 1000);
                    String time = minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
                    times.setText(time);

                    // 每秒钟更新一次
                    handler.postDelayed(this, 1000);
                }
            }, 1000);
        }



    }




    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null) {
            videoView.pause(); // 暂停视频
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
        if (videoView != null && isPlaying) {
            videoView.start(); // 继续播放视频
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (videoView != null) {
            videoView.stopPlayback(); // 停止视频播放
        }
    }

    @Override
    public void showLoading() {
        // 显示加载指示器
    }

    @Override
    public void hideLoading() {
        // 隐藏加载指示器
    }

    @Override
    public void updateProgress(int progress) {
        seekBar.setProgress(progress);
    }

    @Override
    public void playVideo(String videoPath) {
        if (videoView != null) {
            videoView.stopPlayback(); // 停止当前视频播放
            videoView.setVideoURI(Uri.parse(videoPath)); // 设置新的视频路径
            videoView.start(); // 开始播放视频
        }
    }

    @Override
    public void nextVideo() {
        if (presenter != null && presenter.hasNextVideo()) {
            String nextVideoPath = presenter.getNextVideoPath();
            playVideo(nextVideoPath);
        }
    }

    @Override
    public void previousVideo() {
        if (presenter != null && presenter.hasPreviousVideo()) {
            String previousVideoPath = presenter.getPreviousVideoPath();
            playVideo(previousVideoPath);
        }
    }
}